//
//  KLAddLockGroupVC.m
//  KISSLOCK
//
//  Created by 陈宾鹏 on 17/2/21.
//  Copyright © 2017年 陈宾鹏. All rights reserved.
//

#import "KLAddLockGroupVC.h"
#import "HemaConst.h"
#import "Masonry.h"
#import "KLHelp.h"
#import "HemaFunction.h"
#import "JRToast.h"
#import "KLHttpAPI.h"

@interface KLAddLockGroupVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property(nonatomic,strong) UIView *headView;
@property(nonatomic,strong) UITextField *nameField;
@property(nonatomic,strong) UILabel *numLabel;
@property(nonatomic,strong) UITableView *lockListTV;
@property(nonatomic,strong) UIButton *saveBtn;

@property(nonatomic,strong) NSMutableArray *selectLock;
@property(nonatomic,strong) NSMutableArray *lock_list_arr;
@end

@implementation KLAddLockGroupVC
-(UITableView *)lockListTV{
    if(!_lockListTV){
        _lockListTV = [[UITableView alloc]init];
        _lockListTV.delegate = self;
        _lockListTV.dataSource = self;
        _lockListTV.bounces = NO;
        _lockListTV.separatorInset = UIEdgeInsetsMake(0, -40, 0, 0);
        [_lockListTV setEditing:YES];
        _lockListTV.tableFooterView = [[UIView alloc]init];
    }
    return _lockListTV;
}

-(NSMutableArray *)selectLock{
    if(!_selectLock){
        _selectLock = [NSMutableArray array];
    }
    return _selectLock;
}

-(NSMutableArray *)lock_list_arr{
    if(!_lock_list_arr){
        _lock_list_arr = [NSMutableArray array];
        [_lock_list_arr addObjectsFromArray:self.firstMaster];
        [_lock_list_arr addObjectsFromArray:self.secondMaster];
    }
    return _lock_list_arr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGB_UI_COLOR(242, 242, 242);
    self.navigationItem.title = @"添加钥匙串";
    [KLHelp navSet:self doBackHandeler:^(UIButton *backButton) {
        [backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    }];
    //设置界面UI
    [self mainUISet];
}-(void)doBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)mainUISet{
    //设置头视图
    self.headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, 150)];
    self.headView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.headView];
    //设置钥匙串图标
    UIView *boardView = [[UIView alloc]init];
    boardView.layer.masksToBounds = YES;
    boardView.layer.cornerRadius = 8;
    boardView.layer.borderWidth = 0.6;
    boardView.layer.borderColor = [UIColor blackColor].CGColor;
    [self.headView addSubview:boardView];
    [boardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.width.mas_equalTo(70);
        make.height.mas_equalTo(70);
        make.centerY.equalTo(self.headView);
    }];
    UIImageView *keysImg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"钥匙-线"]];
    [boardView addSubview:keysImg];
    [keysImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(60);
        make.center.equalTo(boardView);
    }];
    //设置文字lable
    UILabel *groupName = [[UILabel alloc]init];
    groupName.textColor = RGB_UI_COLOR(115, 115, 115);
    groupName.text = @"钥匙串名:";
    groupName.font = [UIFont systemFontOfSize:16 weight:0.7];
    [self.headView addSubview:groupName];
    [groupName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(boardView).with.offset(80);
        make.top.mas_equalTo(42);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(30);
    }];
    UILabel *lockNum = [[UILabel alloc]init];
    lockNum.textColor = RGB_UI_COLOR(115, 115, 115);
    lockNum.text = @"包含锁数量:";
    lockNum.font = [UIFont systemFontOfSize:16 weight:0.7];
    [self.headView addSubview:lockNum];
    [lockNum mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(boardView).with.offset(80);
        make.bottom.mas_equalTo(-42);
        make.width.mas_equalTo(100);
        make.height.mas_equalTo(30);
    }];
    //设置填写组名字的textfield
    self.nameField = [[UITextField alloc]init];
    self.nameField.borderStyle = UITextBorderStyleRoundedRect;
    self.nameField.font = [UIFont systemFontOfSize:16];
    self.nameField.textColor = RGB_UI_COLOR(255, 105, 180);
    self.nameField.returnKeyType = UIReturnKeyDone;
    self.nameField.tintColor = RGB_UI_COLOR(255, 105, 180);
    self.nameField.placeholder = @"填写钥匙串名";
    [self.nameField becomeFirstResponder];
    self.nameField.delegate = self;
    [self.headView addSubview:self.nameField];
    [self.nameField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-15);
        make.left.equalTo(groupName).with.offset(95);
        make.height.mas_equalTo(26);
        make.centerY.equalTo(groupName);
    }];
    //设置锁的数量
    self.numLabel = [[UILabel alloc]init];
    self.numLabel.font = [UIFont systemFontOfSize:16];
    self.numLabel.textColor = RGB_UI_COLOR(255, 105, 180);
    self.numLabel.text = [NSString stringWithFormat:@"%zd把",self.selectLock.count];
    [self.headView addSubview:self.numLabel];
    [self.numLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(groupName).with.offset(95);
        make.height.mas_equalTo(27);
        make.centerY.equalTo(lockNum);
    }];
    //设置tableview
    [self.view addSubview:self.lockListTV];
    [self.lockListTV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.top.equalTo(self.headView).with.offset(150);
        make.bottom.mas_equalTo(-70);
    }];
    //设置保存按钮
    self.saveBtn = [[UIButton alloc]init];
    self.saveBtn.backgroundColor = RGB_UI_COLOR(8, 128, 181);
    [self.saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    self.saveBtn.titleLabel.font = [UIFont systemFontOfSize:19 weight:0.7];
    self.saveBtn.layer.masksToBounds = YES;
    self.saveBtn.layer.cornerRadius = 5;
    [self.saveBtn addTarget:self action:@selector(doSave:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.saveBtn];
    [self.saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(44);
        make.bottom.mas_equalTo(-13);
    }];
}-(void)doSave:(UIButton *)sender{
    NSString *text = [self.nameField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if([HemaFunction xfunc_check_strEmpty:text]){
        [JRToast showWithText:@"为该钥匙串取个名字！"];
        return ;
    }
    if(self.selectLock.count == 0){
        [JRToast showWithText:@"请选择至少一把锁来创建钥匙串"];
        return ;
    }
    [KLHelp showHUDAddedTo:self.view animated:YES];
    [KLHttpAPI requestKeyBrunchWithGroupName:text lock_list:self.selectLock completionHandler:^(MKNetworkOperation *operation) {
        NSLog(@"新建组返回数据:%@",operation.responseString);
        NSDictionary *result = operation.responseJSON;
        NSString *isSuccess = [result objectForKey:@"success"];
        if(isSuccess.integerValue == 1){
            [[NSNotificationCenter defaultCenter] postNotificationName:@"brunchSuccess" object:nil];
            [self.navigationController popViewControllerAnimated:YES];
            [JRToast showWithText:@"创建成功"];
        }else{
            [JRToast showWithText:[result objectForKey:@"msg"]];
        }
        [KLHelp hideAllHUDsForView:self.view animated:YES];
    } errorHandler:^(NSString *error) {
        [KLHelp hideAllHUDsForView:self.view animated:YES];
        [JRToast showWithText:error];
    }];
}

#pragma mark - UITableViwDelegate和dataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.lock_list_arr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LockListTV"];
    if(!cell){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"LockListTV"];
    }else{
        //删除cell的所有子视图
        while ([cell.contentView.subviews lastObject] != nil){
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    NSDictionary *lockDic = self.lock_list_arr[indexPath.row];
    
    UIImageView *iv = [[UIImageView alloc]init];
    iv.image = [UIImage imageNamed:@"lockround"];
    [cell.contentView addSubview:iv];
    [iv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(cell);
        make.size.mas_equalTo(CGSizeMake(29, 38));
        make.left.equalTo(cell.contentView).with.offset(10);
    }];
    
    UILabel *nameLabel = [[UILabel alloc]init];
    nameLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    nameLabel.text = [NSString stringWithFormat:@"别名：%@",[lockDic objectForKey:@"name"]];
    nameLabel.font = [UIFont systemFontOfSize:16];
    nameLabel.textAlignment = NSTextAlignmentLeft;
    [cell.contentView addSubview:nameLabel];
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(cell.contentView).with.offset(3);
        make.right.equalTo(cell.contentView).with.offset(-10);
        make.height.mas_equalTo(30);
        make.left.equalTo(iv).with.offset(40);
    }];
    
    UILabel *addressLabel = [[UILabel alloc]init];
    addressLabel.lineBreakMode = NSLineBreakByTruncatingMiddle;
    addressLabel.text = [NSString stringWithFormat:@"地址：%@",[lockDic objectForKey:@"address"]];
    addressLabel.font = [UIFont systemFontOfSize:14];
    addressLabel.textColor = RGB_UI_COLOR(120, 120, 120);
    addressLabel.textAlignment = NSTextAlignmentLeft;
    [cell.contentView addSubview:addressLabel];
    [addressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(cell.contentView).with.offset(-3);
        make.right.equalTo(cell.contentView).with.offset(-10);
        make.height.mas_equalTo(30);
        make.left.equalTo(iv).with.offset(40);
    }];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *lockDic = self.lock_list_arr[indexPath.row];
    NSString *lock_id = [lockDic objectForKey:@"id"];
    NSDictionary *dic = [NSDictionary dictionaryWithObject:lock_id forKey:@"lock_id"];
    [self.selectLock addObject:dic];
    self.numLabel.text = [NSString stringWithFormat:@"%zd把",self.selectLock.count];
    NSLog(@"%@",self.selectLock);
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *lockDic = self.lock_list_arr[indexPath.row];
    NSString *lock_id = [lockDic objectForKey:@"id"];
    NSDictionary *dic = [NSDictionary dictionaryWithObject:lock_id forKey:@"lock_id"];
    [self.selectLock removeObject:dic];
    self.numLabel.text = [NSString stringWithFormat:@"%zd把",self.selectLock.count];
    NSLog(@"%@",self.selectLock);
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView*)tableView editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15.f;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

#pragma mark - UITextFieldDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.headView endEditing:YES];
    return YES;
}
@end
